﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Primitives;

namespace Core
{
    [Serializable]
    public class SinglePolyline
    {
        private CircularArray<SinglePoint> m_points;
        public CircularArray<SinglePoint> Points
        {
            get
            {
                return m_points;
            }
        }

        private int m_type;
        public int Type
        {
            get { return m_type; }
            set { m_type = value; }
        }

        public int Length
        {
            get { return m_points.Length; }
        }

        private SingleRect m_boundingRect;
        public SingleRect BoundingRectangle
        {
            get
            {
                return m_boundingRect;
            }
        }

        public SinglePolyline(SinglePoint[] points, int type)
        {
            m_points = new CircularArray<SinglePoint>(points);
            m_type = type;

            m_boundingRect = new SingleRect(m_points[0], m_points[0]);

            foreach (var p in points)
            {
                if (p.X < m_boundingRect.Left)
                    m_boundingRect.Left = p.X;

                if (p.X > m_boundingRect.Right)
                    m_boundingRect.Right = p.X;

                if (p.Y < m_boundingRect.Bottom)
                    m_boundingRect.Bottom = p.Y;

                if (p.Y > m_boundingRect.Top)
                    m_boundingRect.Top = p.Y;
            }
        }
        public SingleSegment GetSegment(int i)
        {
            return new SingleSegment(m_points[i - 1], m_points[i]);
        }
        public SinglePolyline AddIntermediatePoints(int pointsPerSegment = 1)
        {
            int k = m_points.Length;
            SinglePoint[] newPoints = new SinglePoint[k * (pointsPerSegment + 1)];
            int added = 0;
            
            for (int i = 1; i <= k; i++)
            {
                SinglePoint first = m_points[i - 1];
                SinglePoint second = m_points[i];

                newPoints[added++] = first;

                for (int j = 0; j < pointsPerSegment; j++)
                {
                    float relPosition = (j + 1.0f) / (pointsPerSegment + 1.0f);
                    SinglePoint intermediate = first * relPosition + (1 - relPosition) * second;
                    newPoints[added++] = intermediate;
                }
            }

            return new SinglePolyline(newPoints, m_type);
        }    
    }
}
